using SqlSugar;
using Rabbit3.Api.Models;
using Rabbit3.Api.Dto;
using AutoMapper;
using Microsoft.Extensions.Caching.Memory;

namespace Rabbit3.Api.Services
{
    /// <summary>
    /// 优化的养殖信息服务实现
    /// </summary>
    public class OptimizedFarmingService : OptimizedBaseService, IFarmingService
    {
        public OptimizedFarmingService(ISqlSugarClient db, IMapper mapper, IMemoryCache cache, ILogger<OptimizedFarmingService> logger)
            : base(db, mapper, cache, logger)
        {
        }

        /// <summary>
        /// 根据溯源信息ID获取养殖信息 - 优化版本
        /// </summary>
        public async Task<FarmingResponseDto?> GetByTraceabilityIdAsync(int traceabilityId)
        {
            var cacheKey = $"{CACHE_PREFIX_FARMING}traceability_{traceabilityId}";
            
            return await GetOrSetCacheAsync(cacheKey, async () =>
            {
                var entity = await _db.Queryable<FarmingInfo>()
                    .Where(x => x.TraceabilityId == traceabilityId && !x.IsDeleted)
                    .FirstAsync();

                if (entity == null)
                    return null;

                var response = _mapper.Map<FarmingResponseDto>(entity);

                // 并行查询免疫信息和企业信息
                var (immunityInfos, enterpriseInfo) = await ExecuteParallelAsync(
                    () => _db.Queryable<ImmunityInfo>()
                        .Where(x => x.FarmingInfoId == entity.Id && !x.IsDeleted)
                        .OrderBy(x => x.FarmingDays)
                        .ToListAsync(),
                    () => _db.Queryable<EnterpriseInfo>()
                        .Where(x => x.TraceabilityId == traceabilityId && x.StageType == "养殖" && !x.IsDeleted)
                        .FirstAsync()
                );

                response.ImmunityInfos = _mapper.Map<List<ImmunityResponseDto>>(immunityInfos);
                
                if (enterpriseInfo != null)
                {
                    response.EnterpriseInfo = _mapper.Map<EnterpriseResponseDto>(enterpriseInfo);
                }

                return response;
            });
        }

        /// <summary>
        /// 根据ID获取养殖信息 - 优化版本
        /// </summary>
        public async Task<FarmingResponseDto?> GetByIdAsync(int id)
        {
            var cacheKey = $"{CACHE_PREFIX_FARMING}{id}";
            
            return await GetOrSetCacheAsync(cacheKey, async () =>
            {
                var entity = await _db.Queryable<FarmingInfo>()
                    .Where(x => x.Id == id && !x.IsDeleted)
                    .FirstAsync();

                if (entity == null)
                    return null;

                var response = _mapper.Map<FarmingResponseDto>(entity);

                // 并行查询免疫信息和企业信息
                var (immunityInfos, enterpriseInfo) = await ExecuteParallelAsync(
                    () => _db.Queryable<ImmunityInfo>()
                        .Where(x => x.FarmingInfoId == entity.Id && !x.IsDeleted)
                        .OrderBy(x => x.FarmingDays)
                        .ToListAsync(),
                    () => _db.Queryable<EnterpriseInfo>()
                        .Where(x => x.TraceabilityId == entity.TraceabilityId && x.StageType == "养殖" && !x.IsDeleted)
                        .FirstAsync()
                );

                response.ImmunityInfos = _mapper.Map<List<ImmunityResponseDto>>(immunityInfos);
                
                if (enterpriseInfo != null)
                {
                    response.EnterpriseInfo = _mapper.Map<EnterpriseResponseDto>(enterpriseInfo);
                }

                return response;
            });
        }

        /// <summary>
        /// 创建养殖信息 - 优化版本
        /// </summary>
        public async Task<FarmingResponseDto> CreateAsync(CreateFarmingDto createDto)
        {
            var entity = _mapper.Map<FarmingInfo>(createDto);
            
            var id = await _db.Insertable(entity).ExecuteReturnIdentityAsync();
            entity.Id = id;

            // 清除相关缓存
            RemoveCachePattern($"{CACHE_PREFIX_FARMING}traceability_{createDto.TraceabilityId}");

            return _mapper.Map<FarmingResponseDto>(entity);
        }

        /// <summary>
        /// 更新养殖信息 - 优化版本
        /// </summary>
        public async Task<FarmingResponseDto?> UpdateAsync(UpdateFarmingDto updateDto)
        {
            var entity = await _db.Queryable<FarmingInfo>()
                .Where(x => x.Id == updateDto.Id && !x.IsDeleted)
                .FirstAsync();
            if (entity == null)
                return null;
            _mapper.Map(updateDto, entity);
            await _db.Updateable(entity).ExecuteCommandAsync();
            // 清除相关缓存
            RemoveCache($"{CACHE_PREFIX_FARMING}{updateDto.Id}");
            RemoveCachePattern($"{CACHE_PREFIX_FARMING}traceability_{entity.TraceabilityId}");
            return _mapper.Map<FarmingResponseDto>(entity);
        }
        /// <summary>
        /// 删除养殖信息 - 优化版本
        /// </summary>
        public async Task<bool> DeleteAsync(int id)
        {
            var entity = await _db.Queryable<FarmingInfo>()
                .Where(x => x.Id == id && !x.IsDeleted)
                .FirstAsync();
            var result = await _db.Updateable<FarmingInfo>()
                .SetColumns(x => new FarmingInfo { IsDeleted = true, UpdatedAt = DateTime.Now })
                .Where(x => x.Id == id && !x.IsDeleted)
                .ExecuteCommandAsync();
            if (result > 0 && entity != null)
            {
                // 清除相关缓存
                RemoveCache($"{CACHE_PREFIX_FARMING}{id}");
                RemoveCachePattern($"{CACHE_PREFIX_FARMING}traceability_{entity.TraceabilityId}");
            }
            return result > 0;
        }
        /// <summary>
        /// 创建免疫信息 - 优化版本
        /// </summary>
        public async Task<ImmunityResponseDto> CreateImmunityAsync(CreateImmunityDto createDto)
        {
            var entity = _mapper.Map<ImmunityInfo>(createDto);
            var id = await _db.Insertable(entity).ExecuteReturnIdentityAsync();
            entity.Id = id;
            // 清除相关缓存
            RemoveCachePattern($"{CACHE_PREFIX_FARMING}traceability_{createDto.FarmingInfoId}");
            return _mapper.Map<ImmunityResponseDto>(entity);
        }
        /// <summary>
        /// 更新免疫信息 - 优化版本
        /// </summary>
        public async Task<ImmunityResponseDto?> UpdateImmunityAsync(UpdateImmunityDto updateDto)
        {
            var entity = await _db.Queryable<ImmunityInfo>()
                .Where(x => x.Id == updateDto.Id && !x.IsDeleted)
                .FirstAsync();
            if (entity == null)
                return null;
            _mapper.Map(updateDto, entity);
            await _db.Updateable(entity).ExecuteCommandAsync();
            // 清除相关缓存
            RemoveCachePattern($"{CACHE_PREFIX_FARMING}traceability_{entity.FarmingInfoId}");
            return _mapper.Map<ImmunityResponseDto>(entity);
        }
        /// <summary>
        /// 删除免疫信息 - 优化版本
        /// </summary>
        public async Task<bool> DeleteImmunityAsync(int id)
        {
            var entity = await _db.Queryable<ImmunityInfo>()
                .Where(x => x.Id == id && !x.IsDeleted)
                .FirstAsync();
            var result = await _db.Updateable<ImmunityInfo>()
                .SetColumns(x => new ImmunityInfo { IsDeleted = true, UpdatedAt = DateTime.Now })
                .Where(x => x.Id == id && !x.IsDeleted)
                .ExecuteCommandAsync();
            if (result > 0 && entity != null)
            {
                // 清除相关缓存
                RemoveCachePattern($"{CACHE_PREFIX_FARMING}traceability_{entity.FarmingInfoId}");
            }
            return result > 0;
        }
        /// <summary>
        /// 创建企业信息 - 优化版本
        /// </summary>
        public async Task<EnterpriseResponseDto> CreateEnterpriseAsync(CreateEnterpriseDto createDto)
        {
            var entity = _mapper.Map<EnterpriseInfo>(createDto);
            
            var id = await _db.Insertable(entity).ExecuteReturnIdentityAsync();
            entity.Id = id;

            // 清除相关缓存
            RemoveCachePattern($"{CACHE_PREFIX_FARMING}traceability_{createDto.TraceabilityId}");
            RemoveCachePattern($"{CACHE_PREFIX_ENTERPRISE}traceability_{createDto.TraceabilityId}");

            return _mapper.Map<EnterpriseResponseDto>(entity);
        }

        /// <summary>
        /// 更新企业信息 - 优化版本
        /// </summary>
        public async Task<EnterpriseResponseDto?> UpdateEnterpriseAsync(UpdateEnterpriseDto updateDto)
        {
            var entity = await _db.Queryable<EnterpriseInfo>()
                .Where(x => x.Id == updateDto.Id && !x.IsDeleted)
                .FirstAsync();
            if (entity == null)
                return null;
            _mapper.Map(updateDto, entity);
            await _db.Updateable(entity).ExecuteCommandAsync();
            // 清除相关缓存
            RemoveCachePattern($"{CACHE_PREFIX_FARMING}traceability_{entity.TraceabilityId}");
            RemoveCachePattern($"{CACHE_PREFIX_ENTERPRISE}traceability_{entity.TraceabilityId}");
            return _mapper.Map<EnterpriseResponseDto>(entity);
        }
        /// <summary>
        /// 删除企业信息 - 优化版本
        /// </summary>
        public async Task<bool> DeleteEnterpriseAsync(int id)
        {
            var entity = await _db.Queryable<EnterpriseInfo>()
                .Where(x => x.Id == id && !x.IsDeleted)
                .FirstAsync();
            var result = await _db.Updateable<EnterpriseInfo>()
                .SetColumns(x => new EnterpriseInfo { IsDeleted = true, UpdatedAt = DateTime.Now })
                .Where(x => x.Id == id && !x.IsDeleted)
                .ExecuteCommandAsync();
            if (result > 0 && entity != null)
            {
                // 清除相关缓存
                RemoveCachePattern($"{CACHE_PREFIX_FARMING}traceability_{entity.TraceabilityId}");
                RemoveCachePattern($"{CACHE_PREFIX_ENTERPRISE}traceability_{entity.TraceabilityId}");
            }
            return result > 0;
        }
    }
}
